package com.sunlake.spring.main.model.course.controller;

import java.util.List;

import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.github.pagehelper.PageInfo;
import com.sunlake.spring.main.common.response.R;
import com.sunlake.spring.main.model.course.dto.CourseQueryDTO;
import com.sunlake.spring.main.model.course.service.CourseService;
import com.sunlake.spring.main.model.course.vo.CourseCategoryVO;
import com.sunlake.spring.main.model.course.vo.CourseDetailVO;
import com.sunlake.spring.main.model.course.vo.CourseItemVO;

import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;

/**
 * 课程控制器
 */
@RestController
@RequestMapping("/api/courses")
@RequiredArgsConstructor
public class CourseController {

    private final CourseService courseService;

    @GetMapping("/featured")
    public R<List<CourseItemVO>> getFeaturedCourses() {
        return courseService.getFeaturedCourses();
    }

    @GetMapping
    public R<PageInfo<CourseItemVO>> getCourses(@Valid CourseQueryDTO queryDTO, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            String message = "参数校验失败";
            FieldError fieldError = bindingResult.getFieldError();
            if (fieldError != null && fieldError.getDefaultMessage() != null) {
                message = fieldError.getDefaultMessage();
            }
            return buildError(message);
        }
        return courseService.getCourses(queryDTO);
    }

    @GetMapping("/{courseId}")
    public R<CourseDetailVO> getCourseDetail(@PathVariable("courseId") Long courseId) {
        return courseService.getCourseDetail(courseId);
    }

    @GetMapping("/categories")
    public R<List<CourseCategoryVO>> getCategories() {
        return courseService.getCategories();
    }

    @SuppressWarnings("unchecked")
    private R<PageInfo<CourseItemVO>> buildError(String message) {
        return (R<PageInfo<CourseItemVO>>) R.error(400, message);
    }
}
